class RouterDeviceService():
    def __init__(self, isDev):
        if isDev:
            self.cache = None
        else:
            self.cache = self.readCpuStats()

    def getMemoryInfo(self):
        with open("/proc/meminfo", "r") as f:
            lines = f.readlines()
        mem_info = {}
        for line in lines:
            key, value = line.split(":")
            mem_info[key.strip()] = value.strip()

        total_memory = int(mem_info["MemTotal"].split()[0])
        free_memory = int(mem_info["MemFree"].split()[0])
        used_memory = total_memory - free_memory
        return total_memory, used_memory, free_memory,  (used_memory / total_memory) * 100

    def readCpuStats(self):
        with open("/proc/stat", "r") as f:
            line = f.readline()
        return [int(value) for value in line.split()[1:]]

    def getCpuUsage(self):
        # 等待一段时间
        start_times = self.cache
        start_idle = start_times[3] + start_times[4]

        # 等待一段时间
        end_times = self.readCpuStats()
        end_idle = end_times[3] + end_times[4]

        # 计算总的CPU时间和空闲时间的变化
        total_delta = sum(end_times) - sum(start_times)
        idle_delta = end_idle - start_idle

        # 计算CPU使用率
        if idle_delta == 0:
            return 0
        cpu_usage = (1.0 - (idle_delta / total_delta)) * 100

        return cpu_usage

    def deviceInfo(self):
        m = self.getMemoryInfo()
        res = {
            'cpu': {
                'usage': self.getCpuUsage(),
            },
            'virtual_memory': {
                'total': m[0],
                'available': m[2],
                'used': m[1],
                'usage': m[3]
            }
        }
        return res